<template>
  <CardHead title="销售表现对比" :filters="filters" @onSelect="onSelect">
    <div class="w-full rounded-lg px-3">
      <div class="w-full bg-white rounded-lg py-3">
        <div class="flex items-center justify-between mb-2 h-[48px] px-3 bg-white">
          <div
            class="flex items-center gap-2"
            @click="showPeoplePicker = true"
            :class="showBounce ? 'animate-elastic-bounce' : ''"
          >
            <p class="text-sm text-[#262626]">共{{ selectedPeopleList.length }}位人员</p>
            <van-icon size="12" name="arrow-down" />
          </div>
        </div>
        <CommonScoreTable :data="cp_list" :columns="columns" />
      </div>
    </div>
  </CardHead>

  <van-action-sheet v-model:show="showPeoplePicker" :lock-scroll="false" title="销售筛选">
    <div class="h-[680px]">
      <choosePeopleView
        v-if="showPeoplePicker"
        :default-team-id="currentDeptId"
        :default-selected-items="selectedPeopleList"
        :defaultSelectedSelf="false"
        :enableCache="true"
        :max-num="5"
        @confirm="onConfirmPeople"
      />
    </div>
  </van-action-sheet>
</template>

<script setup lang="ts">
import CardHead from "@/views/myXmate/myTeam/components/cardHead.vue";
import { computed, ref, Ref, watch, onMounted } from "vue";
import reportOptions from "../reportOptions.json";
import { showToast } from "vant";
import { useMyXmateStore } from "@/store";
import { getUserCompare, ReportDataType, UserCompareParams } from "@/services/myXmate";
import { FilterItem, FilterOptions } from "@/views/myXmate/myTeam/components/cardHead";
import { getUserInfo } from "@/utils/auth";
import choosePeopleView from "@/components/choosePeople/choosePeopleView.vue";
import CommonScoreTable from "@/views/myXmate/components/commonScoreTable.vue";
import { optimizeDecimal } from "@/utils/num";
import { formatCompletionTime, ParameterDateType } from "@/utils/timeTool";

const store = useMyXmateStore();
const orgId = computed(() => getUserInfo().orgId);
const currentDeptId = computed(() => store.noticeBoardPublicParam.currentDept?.id);
const reportType = computed(() => store.noticeBoardPublicParam.reportType);
const startTime = computed(() => store.noticeBoardPublicParam.startDate);
const endTime = computed(() => store.noticeBoardPublicParam.endDate);
const candidateList = computed(() => store.noticeBoardPublicParam.candidateList);

const showPeoplePicker = ref(false);
const selectedPeopleList = ref([]);

const onConfirmPeople = (v: Array<never>) => {
  console.log("onConfirmPeople: ", v);
  showPeoplePicker.value = false;
  selectedPeopleList.value = v;
};

// 销售表现
const currentFilter: Ref<FilterOptions> = ref(reportOptions[0]);
const filters = [
  {
    text: currentFilter.value?.text,
    type: currentFilter.value?.value,
    options: reportOptions,
  },
];

const onSelect = (filterItem: FilterItem) => {
  const { options } = filterItem;
  currentFilter.value = options?.find(
    (temp: FilterOptions) => temp.value === filterItem.value
  );
  getData(true);
};

onMounted(() => {
  setDefaultPeopleList();
  getData();
});

watch([currentDeptId, reportType, selectedPeopleList], () => {
  getData();
});

watch(candidateList, () => {
  setDefaultPeopleList();
  getData();
});

function setDefaultPeopleList() {
  selectedPeopleList.value = candidateList.value.slice(0, 2) || [];
}

function makeParams(): UserCompareParams {
  return {
    orgId: orgId.value,
    deptId: currentDeptId.value,
    dataType: currentFilter.value?.value as ReportDataType,
    params: {
      startTime: formatCompletionTime(startTime.value, ParameterDateType.START_DATE),
      endTime: formatCompletionTime(endTime.value, ParameterDateType.ENE_DATE),
      reportType: reportType.value,
      ssoUserIds: selectedPeopleList.value.map((v) => v?.id),
    },
  } as UserCompareParams;
}

const list = ref([]);
const settings = ref({});
const columns = computed(() => {
  let array = [];
  let isAbility = currentFilter.value.value === ReportDataType.ABILITY;
  let systemColums = isAbility
    ? settings.value.salesAbilityAssesses
    : settings.value.taskCompleteAssesses;
  systemColums = systemColums?.systemAssessments || [];

  systemColums.forEach((item: any) => {
    const { enabled, name } = item;
    if (enabled) {
      array.push({
        label: name,
        prop: name,
        enableSort: true,
        isSocre: true,
        width: name?.length * 10 + 90,
      });
    }
  });

  list.value.forEach(({ scores }) => {
    scores.forEach(({ assessmentName }) => {
      const index = array.findIndex((item) => item.prop === assessmentName);

      if (index === -1) {
        array.push({
          label: assessmentName,
          prop: assessmentName,
          enableSort: true,
          isSocre: true,
          width: assessmentName.length * 10 + 90,
        });
      }
    });
  });
  array = [...new Set(array)];

  console.log("columns: ", array);
  return [
    {
      label: "姓名",
      fixed: true,
      prop: "name",
    },
    ...array,
  ];
});

async function getData(needToast: boolean = false) {
  if (selectedPeopleList.value?.length === 0) {
    if (needToast) {
      showSelectPeopleToast();
    }
    return;
  }
  console.log("getData cp_params: ", makeParams());
  const data = await getUserCompare(makeParams());
  list.value = data.datas;
  settings.value = data.settings;
}

const cp_list = computed(() => {
  if (!columns.value || columns.value.length === 0) return [];
  return list.value.map((item) => {
    const { scores } = item;
    for (let column of columns.value) {
      const prop = column.prop;
      if (prop !== "name") {
        const score = scores?.find(({ assessmentName }) => assessmentName === prop)
          ?.score;
        item[prop] = optimizeDecimal(score) || "-";
      }
    }
    return item;
  });
});

const showBounce = ref(false);
function showSelectPeopleToast() {
  showToast("请先选择对比人员");
  showBounce.value = true;
  setTimeout(() => {
    showBounce.value = false;
  }, 1000); // 动画持续1秒
}
</script>

<style scoped>
@keyframes elastic-bounce {
  0% {
    transform: scale(1);
  }
  30% {
    transform: scale(1.25, 0.75);
  }
  40% {
    transform: scale(0.75, 1.25);
  }
  50% {
    transform: scale(1.15, 0.85);
  }
  65% {
    transform: scale(0.95, 1.05);
  }
  75% {
    transform: scale(1.05, 0.95);
  }
  100% {
    transform: scale(1);
  }
}
.animate-elastic-bounce {
  animation: elastic-bounce 0.7s;
}
</style>
